package com.hanhai.material.config.security;


import com.hanhai.material.common.constant.Constant;
//import com.hanhai.material.common.exception.CaptchaException;
import com.hanhai.material.utils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginHandler extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String url = httpServletRequest.getRequestURI();
        if ("/login".equals(url) && "POST".equals(httpServletRequest.getMethod())) {
            try {
                // 校验验证码
//                validate(httpServletRequest);
            } catch (Exception e) {
                // 交给认证失败处理器
                loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, (AuthenticationException) e);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
    // 校验验证码逻辑
    private void validate(HttpServletRequest httpServletRequest) throws Exception {
        /*获取请求中携带的code和token*/
        String code = httpServletRequest.getParameter("code");
        String token= httpServletRequest.getParameter("token");
//        if (StringUtils.isBlank(code) || StringUtils.isBlank(token)) {
//            throw new CaptchaException("验证码错误");
//        }
        if (!code.equals(redisUtil.hget(Constant.CAPTCHA_KEY, token))) {
            throw new Exception("验证码错误");
        }
        redisUtil.hdel(Constant.CAPTCHA_KEY, token);
    }
}
